package com.wyp168.renrenfilm.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.wyp168.common.utils.R;
import com.wyp168.renrenfilm.core.dto.UserDTO;
import com.wyp168.renrenfilm.core.entity.HomeEntity;
import com.wyp168.renrenfilm.core.feign.RenrenFastFeign;
import com.wyp168.renrenfilm.core.service.HomeService;
import com.wyp168.renrenfilm.core.service.RequireService;
import com.wyp168.renrenfilm.core.vo.HomeReqVO;
import com.wyp168.renrenfilm.core.vo.HomeVO;
import com.wyp168.renrenfilm.core.vo.resp.HomeRespVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/film/home")
public class HomeController {
    @Autowired
    HomeService homeService;

    @Autowired
    RequireService requireService;

    @GetMapping("list")
    public R homeList(HomeReqVO homeReqVO) {
        List< HomeRespVO> list = homeService.list(homeReqVO);
        return R.ok().put("data", list);
    }

    @PostMapping("createHome")
    public R createHome(@RequestBody HomeEntity homeEntity, HttpServletRequest req) {
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return R.error("当前用户尚未登录");
        }

        UserDTO user = requireService.getLoginUserObjByToken(token);

        homeEntity.setOwnerId(user.getUserId());
        homeEntity.setOwnerName(user.getUsername());
        homeEntity.setCurrCount(1L);    //初始化为1
        homeEntity.setStartAt(LocalDateTime.now());
        homeService.saveHomeInfo(homeEntity);
        return R.ok();
    }

    @PostMapping("deleteHome")
    public R deleteHome(@RequestBody(required = true) HomeVO homeVO) {
        if (homeVO.getHomeId() == 0) {
            return R.error("删除失败，homeId不存在或有误");
        }
        homeService.saveStateAndDeleteHomeById(homeVO.getHomeId());
        return R.ok();
    }
}
